package com.example.jwtauthdemo.service;

import com.example.jwtauthdemo.mapper.UserMapper;
import com.example.jwtauthdemo.model.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;  // 替换为 UserMapper

    public UserDetailsServiceImpl(UserMapper userMapper) {  // 注入 UserMapper
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findByUsername(username)  // 使用 Mapper 方法
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + username));

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                user.getRole() == 2 ? Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN")) : 
                user.getRole() == 1 ? Arrays.asList(new SimpleGrantedAuthority("ROLE_TEACHER")) : 
                Arrays.asList(new SimpleGrantedAuthority("ROLE_STUDENT"))
        );
    }
}